<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\cdc;

use app\command\BaseWork;
use app\command\DailyStatWork;
use app\enum\AccountEnum;
use app\model\CrontabTaskModel;
use app\service\cdc\cost\flow\FlowInterface;
use app\service\cdc\cost\TaskAccountService;
use app\service\client\AccountService;
use app\service\CrontabTaskService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class CostMediaCostPullWork extends BaseWork implements DailyStatWork
{
    public ?string $tag = null;

    public function setTag($tag = null): bool
    {
        if (! is_null($tag)) {
            $this->tag = $tag;
        }
        return true;
    }

    public function getTag(): ?string
    {
        return strval($this->tag);
    }

    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('cost_media_cost_pull_work');
        // 设置参数
        $this->setDescription('拉取数据脚本')
            ->addArgument('task_type', Argument::REQUIRED, '任务类型  1：账户 2：视频  3：图片')
            ->addArgument('date_type', Argument::REQUIRED, '日期类型 1昨日  2今日')
            ->addArgument('media_id', Argument::OPTIONAL, '媒体id')
            ->addArgument('date', Argument::OPTIONAL, '日期 Ymd')
            ->setHelp('php think cost_media_cost_pull_work [task_type] [date_type] [media_id] [date]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $mediaId = intval($input->getArgument('media_id'));
        $taskType = intval($input->getArgument('task_type'));
        $dateType = $input->getArgument('date_type');
        if ($dateType == 1) {
            $dateInt = date('Ymd', strtotime('-1 day'));
        } elseif ($dateType == 2) {
            $dateInt = date('Ymd');
        } else {
            $dateInt = $input->getArgument('date') ?: date('Ymd', strtotime('-1 day'));
        }
        $dateInt = intval($dateInt);
        $this->setTag($mediaId . '-' . $taskType);

        $this->getOutputMessage('拉取数据脚本开始');
        $redisKey = TaskAccountService::getTaskRedisKey($taskType, $mediaId, $dateInt);
        if (! $redisKey) {
            $this->getOutputMessage('队列获取失败！');
            return false;
        }

        $redis = Cache::store('redis')->handler();
        if ($redis->lLen($redisKey) <= 0) {
            if ($dateType == 1) {
                // 昨日更新任务执行时间
                CrontabTaskService::setSingleTask($this);
            }

            $this->getOutputMessage('队列为空！');
            return false;
        }

        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;
        while (time() - $t <= $runTime) {
            $id = $redis->lPop($redisKey);
            if (! $id) {
                break;
            }

            try {
                $service = TaskAccountService::getCostFlowService($taskType);
                if (! $service instanceof FlowInterface) {
                    $this->getOutputMessage('服务类型未知');
                    continue;
                }

                $taskAccountModel = TaskAccountService::getTaskAccountModel(intval($id));
                if (! $taskAccountModel->getKey()) {
                    $this->getOutputMessage('获取任务模型失败，id:' . $id);
                    continue;
                }

                // 判断是否停投
                $clientAccount = AccountService::getAccountModel($taskAccountModel->getAttr('account_id'));
                if ($clientAccount->getAttr('status') == AccountEnum::PUTTING_STATUS_STOP) {
                    $this->getOutputMessage('账户:' . $taskAccountModel->getAttr('advertiser_id') . '已停投！');
                    continue;
                }

                $res = $service->getDailyData($taskAccountModel);
                if (! $res) {
                    // 插入队尾
                    $redis->rPush($redisKey, $id);
                    $this->getOutputMessage('任务id：' . $id . '错误：' . $service::getError(0));
                }
            } catch (\Exception $e) {
                $this->getOutputMessage('_id' . $id . '错误：' . $e->getMessage());
                echo $e->getLine() . PHP_EOL;
                echo $e->getFile() . PHP_EOL;
                echo $e->getTraceAsString() . PHP_EOL;
            }
        }

        $this->getOutputMessage('拉取数据脚本结束');
    }
}
